package java21demo;

import java.lang.Thread.Builder.OfVirtual;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class VirtualThreadTest2 {
	public static void vt1Unstarted() throws InterruptedException {
		Thread.Builder builder = Thread.ofVirtual().name("vt1Unstarted");
		Thread thread = builder.unstarted(() -> {
			String name = Thread.currentThread().getName();
			System.out.println("I'm " + name + ".");
			
		});
		thread.start();
		thread.join(); // 让主线程等待该线程中止，这样才能看到该虚拟线程打印的信息
		
	}

	public static void vt2Start() throws InterruptedException {
		// 也可使用Thread.startVirtualThread(thread) 等同于Thread.ofVirtual().start(task)
		Thread thread = Thread.ofVirtual().name("vt2Start").start(() -> {
			String name = Thread.currentThread().getName();
			System.out.println("I'm " + name + ".");
		});
		thread.join();
	}

	public static void vt3ThreadFactory() throws InterruptedException {
		ThreadFactory vtFactory = Thread.ofVirtual().factory();
		Thread thread = vtFactory.newThread(() -> {
			String name = Thread.currentThread().getName();
			System.out.println("I'm " + name + ".");
		});
		thread.setName("vt3ThreadFactory");
		thread.start();
		thread.join();
	}

	public static void main(String[] args) throws InterruptedException {
		vt1Unstarted();
		vt2Start();
		vt3ThreadFactory();
	}

}
